<template>
    <input type="text" ref="input" :value="value">
</template>

<script>
export default {
    name: 'taginput',
    props: ['value'],
    data() {
        return {
            selectize: null,
            syncValue: null,
        }
    },
    mounted(){
        this.rebind()
    },
    watch: {
        value(val) {
            if (_.isEqual(this.syncValue, val)) {
                return
            }
            this.syncValue = _.clone(val)
            console.log('[taginput] watch')
            this.rebind()
        }
    },
    methods: {
        rebind() {
            if (this.selectize) {
                this.selectize.destroy()
            }
            setTimeout(() => {
                this.selectize = $(this.$refs.input).selectize({
                    plugins: ['remove_button'],
                    delimiter: ',',
                    create: true,
                    persist: false,
                    onChange: (value) => {
                        const tags = (value.length === 0 ? [] : _.split(value, ','))
                        if (_.isEqual(tags, this.syncValue)) {
                            return
                        }
                        this.syncValue = _.clone(tags)
                        this.$emit('input', tags)
                        console.log('[taginput] emit')
                    }
                })[0].selectize
            }, 0)
        }
    }
}
</script>

